import { request } from '@/service/request';
import { ChannelUtils } from '@/utils/channel';
import { getSystemSetting, getAppAuthorizeSetting, getDeviceInfo, getWindowInfo, getAppBaseInfo } from '@tarojs/taro';

// 医院列表接口类型定义
interface HospitalItem {
    id: string;
    name: string;
    address?: string;
    phone?: string;
    [key: string]: any;
}

interface HospitalListResponse {
    records: HospitalItem[];
    total: number;
    size: number;
    current: number;
    pages: number;
}

/**
 * 渠道相关API服务
 */
export class ChannelService {
    /**
     * 上报渠道访问信息
     */
    static async reportChannelAccess() {
        const channelInfo = ChannelUtils.getChannelInfo();
        if (!channelInfo.isFromThirdParty) {
            return;
        }

        try {
            // 使用新的 API 获取系统信息
            const [systemSetting, appAuthorizeSetting, deviceInfo, windowInfo, appBaseInfo] = await Promise.all([
                getSystemSetting(),
                getAppAuthorizeSetting(),
                getDeviceInfo(),
                getWindowInfo(),
                getAppBaseInfo()
            ]);
            
            const systemInfo = {
                systemSetting,
                appAuthorizeSetting,
                deviceInfo,
                windowInfo,
                appBaseInfo
            };
            
            // const response = await request.post('/api/channel/access', {
            //     channelId: channelInfo.channelId,
            //     accessTime: channelInfo.timestamp,
            //     systemInfo: systemInfo,
            //     // 可以添加更多信息
            // }, {
            //     useErrMsg: false
            // });
            // return response;
        } catch (error) {
            console.error('渠道访问上报失败:', error);
            // 失败时不阻塞主流程
        }
    }

    /**
     * 上报用户注册信息（带渠道）
     */
    static async reportUserRegister(userInfo: any) {
        const channelInfo = ChannelUtils.getChannelInfo();
        
        try {
            const response = await request.post('/api/channel/register', {
                ...userInfo,
                channelId: channelInfo.channelId,
                registerTime: Date.now(),
                isFromThirdParty: channelInfo.isFromThirdParty
            }, {
                useErrMsg: false
            });
            return response;
        } catch (error) {
            console.error('用户注册上报失败:', error);
            // 失败时不阻塞主流程
        }
    }

    /**
     * 获取渠道配置信息
     */
    static async getChannelConfig(channelId: string) {
        try {
            const response = await request.get(`/api/channel/config/${channelId}`, {}, {
                useErrMsg: false
            });
            return response;
        } catch (error) {
            console.error('获取渠道配置失败:', error);
            return null;
        }
    }

    /**
     * 验证渠道有效性
     */
    static async validateChannel(channelId: string) {
        try {
            const response = await request.get(`/api/channel/validate/${channelId}`, {}, {
                useErrMsg: false
            });
            // 根据响应格式处理数据
            if (response.error) {
                console.error('渠道验证失败:', response.error);
                return false;
            }
            return response.success?.valid || false;
        } catch (error) {
            console.error('验证渠道失败:', error);
            return false;
        }
    }

    /**
     * 根据渠道ID查询医院列表
     */
    static async getHospitalListByChannel(pageNo: number = 1, pageSize: number = 10) {
        const shopid = ChannelUtils.getShopId();
        
        try {
            // 构建查询参数
            const params: any = {
                pageNo,
                pageSize
            };
            
            // 如果有渠道ID，添加到查询参数中
            if (shopid) {
                // params.id = shopid;
                params.oldNum = shopid;
            }
            
            const response = await request.get<HospitalListResponse>('/nurse_hospital/nurseHospital/rootList', params, {
                useErrMsg: true
            });
            
            if (response.error) {
                console.error('获取医院列表失败:', response.error);
                return null;
            }
            
            return response.success;
        } catch (error) {
            console.error('获取医院列表失败:', error);
            return null;
        }
    }

    /**
     * 根据渠道ID和区域查询医院列表
     */
    static async getHospitalListByChannelAndArea(area: string, pageNo: number = 1, pageSize: number = 10) {
        const channelId = ChannelUtils.getChannelId();
        
        try {
            // 构建查询参数
            const params: any = {
                area,
                pageNo,
                pageSize
            };
            
            // 如果有渠道ID，添加到查询参数中
            if (channelId) {
                params.channelId = channelId;
            }
            
            const response = await request.get<HospitalListResponse>('/nurse_hospital/nurseHospital/queryByArea', params, {
                useErrMsg: true
            });
            
            if (response.error) {
                console.error('根据区域获取医院列表失败:', response.error);
                return null;
            }
            
            return response.success;
        } catch (error) {
            console.error('根据区域获取医院列表失败:', error);
            return null;
        }
    }

    /**
     * 获取渠道相关的医院统计信息
     */
    static async getChannelHospitalStats() {
        const channelId = ChannelUtils.getChannelId();
        
        if (!channelId) {
            return null;
        }
        
        try {
            const response = await request.get('/api/channel/hospital/stats', {
                channelId
            }, {
                useErrMsg: false
            });
            
            if (response.error) {
                console.error('获取医院统计信息失败:', response.error);
                return null;
            }
            
            return response.success;
        } catch (error) {
            console.error('获取医院统计信息失败:', error);
            return null;
        }
    }
}
